import time

from flask_appbuilder.security.sqla.models import User
import jwt
from sqlalchemy import BigInteger, Column, Integer, String, Text

from myapp.const.user import EnumUserRole, EnumUserStatus
from myapp.third.auth.permission import get_cached_roles_for_user_by_id, set_roles_for_user_by_id
from myapp.utils.exception import log_exception


class MyUser(User):
    __tablename__ = 'ab_user'
    org = Column(String(200))  # Organization
    nickname = Column(String(100), nullable=True, default='默认昵称')
    info = Column(Text(65536), nullable=True, default='', comment='用户个人信息')
    phone = Column(String(20), nullable=True, default='', comment='手机号码')
    status = Column(Integer, nullable=False, server_default='1', default=1, comment='用户状态')
    expired_time = Column(
        BigInteger, nullable=False, server_default='0', default=0, comment='到期时间'
    )  # 时间戳
    taichu = Column(
        String(100), nullable=False, default='', server_default='', comment='taichu账号'
    )
    tenant_id = Column(
        String(100), nullable=False, default='', server_default='', comment='租户id'
    )

    def get_full_name(self):
        return self.username

    def __repr__(self):
        return self.username

    def get_status(self):
        status = EnumUserStatus.get_name(self.status)
        if status == EnumUserStatus.normal.name and self.expired_time and self.expired_time > 0:
            if int(time.time()) > self.expired_time:
                status = EnumUserStatus.expired.name

        return status

    def get_roles(self):
        # if getattr(self, '_roles', None) is not None:
        #     return self._roles

        ret = []

        if self.taichu == '':
            return ret

        with log_exception:
            ret = get_cached_roles_for_user_by_id(self.taichu)
            # self._roles = ret

        return ret

    def set_roles(self, roles: list[str]):
        set_roles_for_user_by_id(self.taichu, roles)
        # self._roles = roles

    @property
    def is_super_admin(self):
        """超级管理员"""

        return self.id == 1

    @property
    def is_tenant_admin(self):
        """租户管理员"""
        return self.tenant_id == self.username

    @property
    def is_admin(self):
        if self.is_super_admin:
            return True

        if EnumUserRole.Admin.value in self.get_roles():
            return True

        return False

    def is_operation(self):
        try:
            user_roles = [role.name.lower() for role in list(self.roles)]
            if 'operation' in user_roles:
                return True
        except Exception:
            pass

        return False

    @property
    def secret(self):
        if self.changed_on:
            pass
            # help(self.changed_on)
            # timestamp = int(func.date_format(self.changed_on))
            # timestamp = int(self.changed_on.timestamp())
            payload = {
                'iss': self.username
                # "iat": timestamp,  # Issue period
                # "nbf": timestamp,  # Effective Date
                # "exp": timestamp + 60 * 60 * 24 * 30 * 12,  # Valid for 12 months
            }

            global_password = 'myapp'
            encoded_jwt = jwt.encode(payload, global_password, algorithm='HS256')
            encoded_jwt = encoded_jwt.decode('utf-8')
            return encoded_jwt
        return ''
